import React, { Component, PropTypes } from 'react';
import Echarts from 'echarts';
import { connect } from 'dva'
import {
  Input,
  Button,
  Select,
  Form,
  Modal,
  Row,
  Col,
  Icon,
  Calendar,
  Cascader,
  message,
} from 'antd';
import style from './home.less';
import styles from '../common.less';
import $ from 'jquery';
import Service from '../../service';
import '../../util/jquery.form.min'; // 图片上传
import NumberPlay from '../../util/numberPlay';
var map, point;
const Search = Input.Search;
const FormItem = Form.Item;
const createForm = Form.create;
const Option = Select.Option;

const formItemLayout = {
  labelCol: {
    span: 5
  },
  wrapperCol: {
    span: 19
  }
};
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      edit: false,
      avatar: '',
      makerlist: [],
      points: [], // 点位列表存储
      makerArr: [],   // 比较是不是当前地图定点
      polylineArr: [],   // 轨迹数据
      markersArr: [],
      imeiArr: []   //权限设备列表
    };
  }
  componentDidMount() {
    const token = localStorage.getItem('token');
    // this.props.queryStatistics({ token: token });
    this.props.queryStatistics({ token: token })
    this.entityListFun();
    this.initMap();
  }
  // 地图初始化
  initMap = () => {
    // 　　var me=this;//定义全局对象
    map = new BMap.Map("mapWrap", { enableMapClick: false });  //创建地图
    point = new BMap.Point(120.25965919955, 30.158778336536);    // 创建点坐标(默认) 这里是苏州
    map.centerAndZoom(point, 18);                  　　   //默认缩放比例  其实打开地图的默认等级
    //启用滚轮放大缩小 
    ////添加控件
    var top_left_control = new BMap.ScaleControl({ anchor: BMAP_ANCHOR_TOP_LEFT });// 左上角，添加比例尺 
    var top_left_navigation = new BMap.NavigationControl();  //左上角，添加默认缩放平移控件
    map.addControl(top_left_control);
    map.addControl(top_left_navigation);
    map.enableScrollWheelZoom();　　　　　　　　　　　　//获取缩放等级,这里没什么用写着玩的;
    //获取数据data  这里从自己数据库获取数据 我就省略了. 编辑大概样式()
    // me["data"] = {
    //     '001': { name: 苏州市工业园区, id: 215006, lat: 31.31529999, lon: 120.78209686, point: { ['id_': 001001, name_: 测试点1] } },
    //     '002': { name: 苏州市新区, id: 215003, lat: 33.31529999, lon: 120.78209686, point: { ['id_': 002001, name_: 测试点2] } }
    // }
    // this.labelInfoBox()
    // this.entityListFun();

  }
  // list获取map所有点位信息
  entityListFun = () => {
    let self = this;
    const userData = JSON.parse(localStorage.getItem('userDetail'));
    const token = localStorage.getItem('token');
    let filter = 'deleted:0|sign_id:';
    if (userData.sign) {
      filter = 'deleted:0|sign_id:' + userData.sign;
    } else {
      filter = 'deleted:0|sign_id:0';
    }
    let points = [];
    // self.props.entityList({
    //     params: {
    //         token: token,
    //         filter: filter
    //     },
    //     func: function (data) {
    //         console.log(data)
    //     }
    // })
    $.ajax({
      url: `${Service.baseUrl}/admin/entity/list`,
      type: "post",
      dataType: "json",
      data: {
        token: token,
        // 'ak': 'WPMnV0isjviG14MI8DjSjgk8qC2ahH9n',
        // 'service_id': '211131',
        'filter': filter
      },
      success: function (data) {
        if (data && data.entities) {
          // console.log(data.entities)
          // let isEqualMarks = self.ergodicMarks(data.entities);
          // console.log(11111111111111111111)
          // console.log(self.state.markersArr)
          // console.log(isEqualMarks)
          // if (!isEqualMarks) {
          //     return false;
          // }

          self.setState({
            points: data.entities
          })
          self.addMarksFun(data.entities)
        }

      }
    })

  }
  // 地图定点
  addMarksFun = (points) => {
    // console.log(8888888888888888)
    let self = this;
    let markerArr = points;
    let pointArray = [];
    // 每次定点的时候清空上次点位数据
    self.remove_overlay();
    let imeiArr = self.state.imeiArr;
    // console.log(points)
    // console.log(imeiArr)
    // console.log(222222)
    // console.log(points)
    for (let i in points) {
      var p0 = markerArr[i].latest_location.longitude;
      var p1 = markerArr[i].latest_location.latitude;
      // var maker = self.addMarker(new window.BMap.Point(p0, p1), i);
      // console.log(markerArr[i].latest_location.longitude)
      // console.log(markerArr[i].latest_location.latitude)
      pointArray[i] = new BMap.Point(p0, p1);
      let entity_desc = markerArr[i].entity_desc.split('_');
      var maker = self.addMarker(new window.BMap.Point(p0, p1), i);
      maker.addEventListener("click", function () {
        // 展开抽屉
        self.setState({
          drawerWidth: '0'
        })
        let imei = entity_desc[3];
        let str = imei.split('-');
        // if (self.state.timer1 != null) {
        //     clearInterval(self.state.timer1);
        // }
        self.searchImei(str[1])
        // console.log(poi)
      });
    }

    // map.showMarkers();
    // 让所有点在视野范围内
    // console.log(pointArray);
    map.setViewport(pointArray);
  }
  // 根据点的数组自动调整缩放级别
  setZoom(bPoints) {
    var view = map.getViewport(eval(bPoints));
    var mapZoom = view.zoom;
    var centerPoint = view.center;
    map.centerAndZoom(centerPoint, mapZoom);
  }

  // 添加标注
  addMarker = (point, index) => {
    // console.log(index)
    var myIcon = new BMap.Icon("http://api.map.baidu.com/img/markers.png",
      new BMap.Size(23, 25), {
        offset: new BMap.Size(10, 25),
        imageOffset: new BMap.Size(0, 0 - index * 25)

      });
    var marker = new BMap.Marker(point, { icon: myIcon });
    map.addOverlay(marker);
    return marker;
  }

  addInfoWindow = (marker, poi) => {
    // console.log(poi)
    let self = this;
    let entity_desc = poi.entity_desc.split('_');
    // marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
    let text = '<div class="mapwrap">' + entity_desc[0] + '<span><img src="' + Service.baseUrl + '/' + entity_desc[1] + '" /></span></div>';
    var label = new window.BMap.Label(text, { offset: new window.BMap.Size(20, -10) });
    marker.setLabel(label);
    var clo = "";

    var info = new window.BMap.InfoWindow("<p>" + entity_desc[0] + "</p>"); // 创建信息窗口对象
    label.addEventListener("click", function () {
      // 展开抽屉
      self.setState({
        drawerWidth: '0'
      })
      let imei = entity_desc[3];
      let str = imei.split('-');
      // if (self.state.timer1 != null) {
      //     clearInterval(self.state.timer1);
      // }
      self.searchImei(str[1])
      // console.log(poi)
    });
    var openInfoWinFun = function () {
      // alert(111)
      // this.openInfoWindow(info);
    };
    // map.setViewport(points);
  }
  remove_overlay = () => {
    map.clearOverlays();
  }
 // 在数据库中搜索
 searchImei = (value) => {
  let self = this;
  let token = localStorage.getItem('token');
  self.props.search({
      params: {
          token: token,
          page: 1,
          page_size: 1,
          number: value
      },
      func: function (result) {
          let data = result;
          if (data && data.list.length > 0) {
              let imei = data.list[0].imei;
              self.serarchMap(imei);
              self.setState({
                  devices: data.list[0],
              }, function () {
                  let start = new Date(
                      new Date(new Date().toLocaleDateString()).getTime()
                  )
              })
          }

          self.setState({
              isSearch: true
          });

      }
  })
}
// 搜索调用鹰眼在地图中找到设备信息
serarchMap = (value) => {
  let self = this;
  const token = localStorage.getItem('token');
  $.ajax({
      url: `${Service.baseUrl}/admin/entity/list`,
      type: "POST",
      dataType: "json",
      data: {
          // 'ak': 'WPMnV0isjviG14MI8DjSjgk8qC2ahH9n',
          // 'service_id': '211131',
          token: token,
          'filter': 'entity_names:' + 'imei_' + value
          // 'entity_name': 'name1'
      },
      success: function (data) {
          if (data && data.entities) {
              self.setState({
                  points: data.entities
              })
              self.remove_overlay();
              let start = new Date(
                  new Date(new Date().toLocaleDateString()).getTime()
              )
              if (self.state.timer1 != null) {
                  clearInterval(self.state.timer1);
              }

              self.mapDataInit(self.state.devices.imei, start);
              if (self.state.timerTrail != null) {
                  clearInterval(self.state.timerTrail);
              }
              // 添加轨迹定时器
              self.state.timerTrail = setInterval(() => {
                  // self.circleMarker();
                  self.mapDataInit(value, start, 'refresh');
              }, 10000)
              // self.addMarksFun(data.entities)
          }

      }
  })
}
// 轨迹渲染
mapDataInit = (equip, date, type) => {
  let self = this;
  const token = localStorage.getItem('token');
  let linerArr = [];
  let polylineArr = [];

  let date1 = date / 1000;
  let date2 = (date1 + 3600 * 24);

  $.ajax({
      type: "GET",
      url: `${Service.baseUrl}/admin/entity/track`,
      dataType: "json",
      async: false, //同步
      data: {
          // 'ak': 'WPMnV0isjviG14MI8DjSjgk8qC2ahH9n',
          // 'service_id': '211131',
          token: token,
          'entity_name': 'imei_' + equip,
          'start_time': date1,
          'end_time': date2,
          'is_processed': 1 //是否绑路
      },
      success: function (data) {
          let isEqual = self.ergodicPoints(data.points, equip);
          // console.log(self.state.polylineArr)
          if (isEqual) {
              self.polylineFun(data.points)
          }
      }


  });

}
ergodicPoints = (pointArr, equip) => {
  let self = this;
  let polylineArr = [];
  $.each(pointArr, function (index, item) {
      polylineArr['imei_lat' + equip] = item.latitude;
      polylineArr['imei_lng' + equip] = item.longitude;
  });
  if (self.ArrayIsEqual(polylineArr, self.state.polylineArr)) {
      self.setState({
          polylineArr: polylineArr
      })
      return false;
  } else {
      self.setState({
          polylineArr: polylineArr
      })
      return true;
  }



}
ergodicMarks = (markArr) => {
  let self = this;
  let markersArr = [];

  $.each(markArr, function (index, item) {
      markersArr['lat_' + item.entity_name] = item.latest_location.latitude;
      markersArr['log_' + item.entity_name] = item.latest_location.longitude;
  });
  if (self.ArrayIsEqual(markersArr, self.state.markersArr)) {
      return false;
  } else {
      self.setState({
          markersArr: markersArr
      })
      return true;
  }
}
polylineFun = (pointArr) => {
  let self = this;
  let points = [];
  map.clearOverlays();
  $.each(pointArr, function (index, item) {
      // points.push(new BMap.Point(item.longitude, item.latitude))
      let point = new BMap.Point(item.longitude, item.latitude);
      points.push(point);
  });
  var polyline = new BMap.Polyline(points, {
      enableEditing: false, //是否启用线编辑，默认为false
      enableClicking: false, //是否响应点击事件，默认为true
      strokeWeight: '4', //折线的宽度，以像素为单位
      strokeOpacity: 0.8, //折线的透明度，取值范围0 - 1
      strokeColor: "#33A0D6" //折线颜色
  });
  map.addOverlay(polyline); //增加折线
  map.centerAndZoom(points[pointArr.length - 1], 25);
  // console.log(points)
  // var driving = new BMap.DrivingRoute(map, { renderOptions: { map: map, panel: "r-result", autoViewport: true } });
  // driving.search(new BMap.Point(points[0].lng, points[0].lat), new BMap.Point(points[pointArr.length - 1].lng, points[pointArr.length - 1].lat));
  // driving.setSearchCompleteCallback(function () {
  //     //得到路线上的所有point  
  //     points = driving.getResults().getPlan(0).getRoute(0).getPath();

  //     //画面移动到起点和终点的中间  
  //     let centerPoint = new BMap.Point((points[0].lng + points[points.length - 1].lng) / 2, (
  //         points[0].lat +
  //         points[points.length - 1].lat) / 2);
  //     map.panTo(centerPoint);
  //     //连接所有点  
  //     map.addOverlay(new BMap.Polyline(points, {
  //         strokeColor: 'blue', //线路颜色
  //         strokeWeight: 4,//线路大小
  //         //线路类型(虚线)
  //         strokeStyle: "dashed"
  //     }));

  //     //显示小车子  
  //     let label = new BMap.Label("", {
  //         offset: new BMap.Size(-20, -20)
  //     });
  //     let car = new BMap.Marker(points[0]);
  //     car.setLabel(label);
  //     // map.addOverlay(car);

  // });
}
ArrayIsEqual = (arr1, arr2) => {//判断2个数组是否相等
  if(arr1 && arr2){
      if (arr1 === arr2) {//如果2个数组对应的指针相同，那么肯定相等，同时也对比一下类型
          return true;
      } else {
          if (arr1.length != arr2.length) {
              return false;
          } else {//长度相同
              for (let i in arr1) {//循环遍历对比每个位置的元素
                  if (arr1[i] != arr2[i]) {//只要出现一次不相等，那么2个数组就不相等
                      return false;
                  }
              }//for循环完成，没有出现不相等的情况，那么2个数组相等
              return true;
          }
      }
  }else{
      return false;
  }
  
}
 // 取消搜索
 cancelSearch = () => {
  this.setState({
      isSearch: false,
      searchValue: '',
      drawerWidth: '-275px',
      markersArr: [],
      polylineArr: []
  });

  this.remove_overlay();
  this.entityListFun(); // 重新所有定点
  // 清空轨迹的定时器
  if (this.state.timerTrail != null) {
      clearInterval(this.state.timerTrail);
  }
  // 添加地图定点定时器

  this.state.timer1 = setInterval(() => {
      this.entityListFun();
  }, 10000)
}
  render() {
    const { Statistics,statisticData } = this.props;
    const { getFieldDecorator } = this.props.form;
    // console.log(Statistics);
    return (
      <div className={style.wrap}>
          <div className={style.mapWrap} id="mapWrap">
          </div>
          <div className={style.drawer} style={{ right: this.state.drawerWidth }}>
                  
                    <div className={style.wrap} id="searchWrap" style={{ height: this.state.maxHeight }}>
                        {!this.state.isSearch &&
                            <div className={style.whole}>
                                <h3>基础信息：</h3>
                                {/* 当前区域：<Cascader options={selectBank} onChange={this.onChangeTree} placeholder="请选择具体区域" /> */}
                                <div className={style.line}></div>
                                <p>当前总录入人数：<span className={styles.blue}>{statisticData && statisticData.e_bike_total}</span>人</p>
                                <p>当前区域新增人数：<span className={styles.blue + ' ' + styles.bold}>{statisticData && statisticData.e_bike_new}</span>人</p>
                                <div className={style.line}></div>
                                <p>当前区域违章违法行为：<span className={styles.blue}>{statisticData && statisticData.message_total}</span>起</p>
                            </div>
                        }
                        {this.state.isSearch &&
                            <div className={style.searchCon}>
                                {this.state.devices &&
                                    <ul>
                                        <li>
                                            <h4>快递员信息：</h4>
                                            <p className={styles.blue}>{this.state.devices.realname}</p>
                                            <p>年龄：{this.state.devices.age}</p>
                                            <p>性别：{this.state.devices.sex}</p>
                                            <p>身份证：{this.state.devices.id_card}</p>
                                            <p>联系方式：{this.state.devices.mobile}</p>
                                            <p>紧急联系人号码：{this.state.devices.contact_mobile}</p>
                                            <span className={style.avator}>
                                                <img src={`${Service.baseUrl}/` + this.state.devices.avatar} />
                                            </span>
                                        </li>


                                        <li>
                                            <h4>车辆信息：</h4>
                                            <p>硬件编号：{this.state.devices.imei}</p>
                                            <p>品牌：{this.state.devices.brand}</p>
                                            <p>车辆状态：
                              {this.state.devices.status == "close" && openCloseArr[0]}
                                                {this.state.devices.status == "open" && openCloseArr[1]}
                                            </p>
                                            {/*<p>当月总公里数：3000km</p>*/}
                                            {/* <span className={style.avator}>
                                                <img src={`${Service.baseUrl}/` + this.state.devices.img} />
                                            </span> */}
                                        </li>

                                    </ul>
                                }
                                {this.state.devices && this.state.devices.imei &&
                                    <div className={style.calendar}>
                                        <span>按日期显示轨迹：</span>
                                        <Icon type="calendar" theme="outlined" />
                                        {/*<Input placeholder="" style={{ width: 120,marginLeft:10 }}/>*/}
                                        <div className={style.calendarCon} >
                                            <Calendar fullscreen={false} onPanelChange={this.onPanelChange} onSelect={this.onSelect} />
                                        </div>
                                    </div>
                                }


                                <div className={style.cancel}>
                                    <Button type="primary" onClick={this.cancelSearch}>取消搜索</Button>


                                </div>

                            </div>
                        }
                    </div>
                    <div className={style.drawerShow} onClick={this.showDrawer}><Icon type="caret-right" className={styles.blue} theme="outlined" /></div>
                </div>
      </div>
    )
  }
}

App.contextTypes = {
  router: React.PropTypes.object
}

function mapStateToProps(state, ownProps) {
  // console.log(state)
  return {
    statisticData: state.myHome.Statistics,
    // statisticData: state.home.Statistic,
    loading: !!state.loading.global
  }
}

function dispatchToProps(dispatch) {
  return {
    queryStatistics(payload, params) {
      dispatch({ type: 'myHome/queryStatistics', payload })
    },
    entityList(payload = {}) {
      dispatch({ type: 'myHome/serch', payload })
  },
  search(payload = {}) {
      dispatch({ type: 'myHome/serchfun', payload })
  },
 
  querypersonalList(payload = {}) {
      dispatch({ type: 'myHome/serchMap', payload })
  },
    queryUpdate(payload, params) {
      dispatch({
        type: 'myHome/update',
        payload
      })
    }
  }
}
export default connect(mapStateToProps, dispatchToProps)(Form.create()(App));
